#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<queue>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if (root == nullptr) return {};
        queue<TreeNode*> q;
        vector<int> ret;
        q.push(root);
        while (!q.empty()) {
            int size = q.size();
            while (size--) {
                TreeNode* front = q.front();
                q.pop();
                if (size == 0) ret.push_back(front->val);
                if (front->left) q.push(front->left);
                if (front->right) q.push(front->right);
            }
        }
        return ret;
    }
};

class Solution {
    vector<int> ret;

public:
    vector<int> rightSideView(TreeNode* root) {
        dfs(root, 0);
        return ret;
    }

    void dfs(TreeNode* root, int depth) {
        if (root == nullptr) return;

        if (ret.size() == depth) ret.push_back(root->val);

        dfs(root->right, depth + 1);
        dfs(root->left, depth + 1);
    }
};